<template>
    <div class="userBind-container">
      <el-button icon="ele-Edit" size="small" text="" type="primary" @click="goLogin"> 去登录页 </el-button>
      <el-card class="full-table" shadow="hover" style="margin-top: 8px">
        <el-table
                  :data="tableData"
                  style="width: 100%"
                  v-loading="loading"
                  tooltip-effect="light"
                  row-key="id"
                  border="">
          <el-table-column type="index" label="序号" width="55" align="center"/>
          <!-- <el-table-column prop="dingUserId" label="钉钉UserId" width="200" show-overflow-tooltip="" /> -->
          <el-table-column prop="userId" label="用户表UserId" width="135" show-overflow-tooltip="">
            <template #default="scope">
              <span>{{scope.row.userIdAccount}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140" align="center" fixed="right" show-overflow-tooltip="">
            <template #default="scope">
              <el-button icon="ele-Edit" size="small" text="" type="primary" @click="loginDingDingHandle(scope.row)"> 选择账号登录 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
                  v-model:currentPage="tableParams.page"
                  v-model:page-size="tableParams.pageSize"
                  :total="tableParams.total"
                  :page-sizes="[10, 20, 50, 100, 200, 500]"
                  small=""
                  background=""
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  layout="total, sizes, prev, pager, next, jumper"
      />
      </el-card>
    </div>
  </template>
  
  <script setup lang="ts" name="dingding">
    import { ref,onMounted } from "vue";
    import { ElMessageBox, ElMessage } from "element-plus";
    import { auth } from '/@/utils/authFunction';
    import { getDictDataItem as di, getDictDataList as dl } from '/@/utils/dict-utils';
    import { formatDate } from '/@/utils/formatTime';
    import { NextLoading } from '/@/utils/loading';
    import { pageDingUserBind, deleteUserBind,loginDingDing } from '/@/api/main/userBind';
    import { Local, Session } from '../../../utils/storage';
    import { accessTokenKey, clearTokens, feature, getAPI } from '/@/utils/axios-utils';
    import { useRoute, useRouter } from 'vue-router';
    import { getCode } from '/@/utils/dingtalk';
    import { getUserId} from '/@/api/topSdk/index';
    import { initBackEndControlRoutes } from '/@/router/backEnd';

    const showAdvanceQueryUI = ref(false);
    const loading = ref(false);
    const tableData = ref<any>([]);
    const queryParams = ref<any>({});
    const tableParams = ref({
      page: 1,
      pageSize: 10,
      total: 0,
    });
    const userid : any= ref(null);
    const route = useRoute();
    const router = useRouter();

    // 查询操作
    const handleQuery = async () => {
      loading.value = true;
      queryParams.value.dingUserId = userid.value;
      var res = await pageDingUserBind(Object.assign(queryParams.value, tableParams.value));
      tableData.value = res.data.result?.items ?? [];
      tableParams.value.total = res.data.result?.total;
      loading.value = false;
      if(tableData.value.length == 0){
        router.push('/');
      }
      if(tableParams.value.total == 1){
        await loginDingDingHandle(tableData.value[0]);
      }
    };
    const goLogin = () => {
      router.push('/');
    };
    
    // 改变页面容量
    const handleSizeChange = (val: number) => {
      tableParams.value.pageSize = val;
      handleQuery();
    };
  
    // 改变页码序号
    const handleCurrentChange = (val: number) => {
      tableParams.value.page = val;
      handleQuery();
    };
  
    const loginDingDingHandle = async(row: any) => {
      var res = await loginDingDing(row);
      	// 缓存token
      Local.set(accessTokenKey, res.data.result.accessToken);
      Session.set('token', res.data.result.accessToken);
      console.log(row);
      Local.set('userid', row.dingUserId);
      Session.set('userid', row.dingUserId);

      const isNoPower = await initBackEndControlRoutes();
      if (isNoPower) {
        ElMessage.warning('抱歉，您没有登录权限');
        clearTokens(); // 清空Token缓存
      }
	    router.push('/');
    };

    onMounted(() => {
        NextLoading.done();
        //const router = useRouter();
        //router.push('userBind');
        var dingUserId = Local.get('userid');
        if (dingUserId === null || dingUserId === undefined || dingUserId === '') 
        {
          getCode(async(code)=>{
            var res = await getUserId({code:code});
            dingUserId = res.data.result;
            userid.value = dingUserId;
            handleQuery();
          });
        }else{
          userid.value = dingUserId;
          handleQuery();
        }
    });

    
</script>
  <style scoped>
  :deep(.el-ipnut),
  :deep(.el-select),
  :deep(.el-input-number) {
      width: 100%;
  }
  </style>
  
  